﻿using Application.Commons.Data;
using AutoMapper;
using Domain.Entities.Customers;
using Domain.Events;
using FrameworkCore.Attributes;
using FrameworkCore.Helpers;
using FrameworkCore.Models;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;

namespace NM.Module.Cust.API.Commands.Update;

#nullable disable 

/// <summary>
/// 修改用户
/// </summary>
[Map(typeof(Customer))]
public class UpdateCustomerCommand : IRequest<Result<long>>
{
    /// <summary>
    /// 用户主键
    /// </summary>
    [Required(ErrorMessage = "用户主键必传")]
    public long CustomerId { get; set; }

    /// <summary>
    /// 电子邮箱
    /// </summary>
    public string Email { get; set; }

    /// <summary>
    /// 头像
    /// </summary>
    public string Avatar { get; set; }
}

public class UpdateCustomerCommandHandler : IRequestHandler<UpdateCustomerCommand, Result<long>>
{
    private readonly ApplicationDbContext _context;
    private readonly IMapper _mapper;

    public UpdateCustomerCommandHandler(
        ApplicationDbContext context, 
        IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    public async Task<Result<long>> Handle(UpdateCustomerCommand request, CancellationToken cancellationToken)
    {
        var existEmail = await _context.Customers
           .AnyAsync(x => x.Email == request.Email && x.Id == request.CustomerId, cancellationToken);
        ExceptionHelper.ThrowIfTrue(existEmail, "邮箱已存在");

        var item = await _context.Customers.SingleOrDefaultAsync(x => x.Id == request.CustomerId, cancellationToken);
        ExceptionHelper.ThrowIfNull(item, "用户不存在");

        _mapper.Map(request, item);
        item.AddDomainEvent(new UpdatedEvent<Customer>(item));
        await _context.SaveChangesAsync(cancellationToken);

        return await Result<long>.SucceedAsync(item.Id);
    }
}